﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interactivity;
using System.Windows.Threading;

namespace TheOliver.Controls
{
    public class DoubleClickTrigger : TriggerBase<UIElement>
    {
        private int count = 0;
        private DispatcherTimer _timer;

        public int DoubleClickSpeed
        {
            get { return (int)GetValue(DoubleClickSpeedProperty); }
            set { SetValue(DoubleClickSpeedProperty, value); }
        }

        public static readonly DependencyProperty DoubleClickSpeedProperty = 
            DependencyProperty.Register(
                "DoubleClickSpeed", 
                typeof(int), 
                typeof(DoubleClickTrigger), 
                new PropertyMetadata(500, DoubleClickSpeedChanged));

        private static void DoubleClickSpeedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            // Code for dealing with your property changes
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            this.AssociatedObject.MouseLeftButtonDown += new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown);
        }

        void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (count == 0)
            {
                _timer = new DispatcherTimer();
                _timer.Interval = new TimeSpan(0, 0, 0, 0, DoubleClickSpeed);
                _timer.Tick += new EventHandler(ResetCount);
                _timer.Start();
            }

            count++;

            if (count >= 2)
            {
                this.InvokeActions(null);
            }
        }

        void ResetCount(object sender, EventArgs e)
        {
            count = 0;
            _timer.Stop();
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.MouseLeftButtonDown -= new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown);
        }
    }
}
